<template>
  <a-modal
    :title="title"
    :visible="visible"
    :footer="null"
    cancelText="关闭"
    :bodyStyle="{
      padding: '24px 24px 67px'
    }"
    :width="width"
    :afterClose="handleClose"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div class="flex justify-center">
      <div class="leftTable w-[604px] m-h-[600px] flex flex-col">
        <div class="leftTable-title">{{ type }}库</div>
        <div class="flex flex-col justify-between">
          <div class="flex justify-start items-center my-[16px]">
            <a-cascader
              :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
              change-on-select
              :allowClear="false"
              class="w-[134px] ml-[20px]"
              :field-names="{ label: 'name', value: 'id', children: 'subcateg' }"
              :options="state.classList"
              placeholder="全部分类"
              @change="handleSelectChange"
            >
              <template #suffixIcon>
                <a-tooltip placement="top" color="#fff">
                  <template #title> 双击选中父级 </template>
                  <div class="ellipsis-text"><question-circle-outlined /></div>
                </a-tooltip>
              </template>
            </a-cascader>
            <a-input
              v-model:value.trim="leftState.video_id"
              allowClear
              :maxlength="19"
              :onkeyup="
                () => {
                  if (leftState.video_id) leftState.video_id = leftState.video_id.replace(/\D/g, '')
                }
              "
              :onafterpaste="
                () => {
                  if (leftState.video_id) leftState.video_id = leftState.video_id.replace(/\D/g, '')
                }
              "
              placeholder="影片ID"
              class="w-[150px] mx-[8px]"
            />
            <a-input
              v-model:value="leftState.video_keyword"
              :placeholder="`${type}名称关键词`"
              allowClear
              class="w-[166px] mr-[8px]"
            />
            <a-button type="primary" class="w-[60px]" @click="leftSearch">搜索</a-button>
          </div>
          <div class="flex flex-col justify-between">
            <a-table
              :row-selection="{
                selectedRowKeys: state.leftSelectedRowKeys.concat(rightKeys),
                checkStrictly: false,
                onChange: onSelectChange,
                getCheckboxProps: (record: any) => {
                  return {
                    disabled: rightKeys.includes(record.video_id),
                  }
                }
              }"
              :rowKey="(record:any) => record.video_id"
              :rowClassName="(record: any) => {
                return rightKeys.includes(record.video_id)  ? 'childBg' : ''
              }"
              :columns="leftColumn"
              :pagination="false"
              :data-source="state.filmList"
              size="small"
              :loading="state.leftLoading"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'sort'">
                  <menu-outlined />
                </template>
                <template v-if="column.key === 'video_name'">
                  <a-tooltip placement="top" color="#fff" v-if="record && record.video_name.length > 0">
                    <template #title>
                      {{ record.video_name }}
                    </template>
                    <div class="ellipsis-text">
                      {{ record.video_name }}
                    </div>
                  </a-tooltip>
                  <span v-else>-</span>
                </template>
                <template v-if="column.key === 'video_popularity'">
                  {{ formatNumber(+record.video_popularity) }}
                </template>
                <template v-if="column.key === 'video_price_type'">
                  <a-tooltip placement="top" color="#fff">
                    <template #title>
                      {{ getPriceType(record) }}
                    </template>
                    <div class="ellipsis-text">
                      {{ getPriceType(record) }}
                    </div>
                  </a-tooltip>
                </template>
              </template>
            </a-table>
          </div>
        </div>
        <a-pagination
          @change="handlePaginationChange"
          show-size-changer
          :defaultPageSize="10"
          :pageSizeOptions="['10', '20', '50', '100']"
          :show-total="(total:number)=>`共${total}条`"
          class="flex justify-end p-[16px]"
          :total="queryState.total"
        />
      </div>
      <div class="flex flex-col justify-center w-[4%] mx-[10px] items-center">
        <a-button type="primary" class="mb-[10px]" @click="toLeft" :disabled="rightSelectKeys">
          <template #icon><left-outlined /></template>
        </a-button>
        <a-button type="primary" class="" @click="toRight" :disabled="leftSelectKeys">
          <template #icon><right-outlined /></template>
        </a-button>
      </div>
      <div class="rightTable w-[604px] m-h-[600px]">
        <div class="rightTable-title">已收录{{ includesLength }} 部{{ type }}</div>
        <a-table
          id="filmTable"
          ref="tableRef"
          :row-selection="{
            selectedRowKeys: state.rightSelectedRowKeys,
            checkStrictly: false,
            onChange: onSelectChange2
          }"
          row-key="video_id"
          :pagination="false"
          :columns="rightColumn"
          :data-source="state.includesList"
          size="small"
          :loading="state.rightLoading"
          class="mt-[16px]"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'sort'">
              <menu-outlined />
            </template>
            <template v-if="column.key === 'video_name'">
              <a-tooltip placement="top" color="#fff" v-if="record && record.video_name.length > 0">
                <template #title>
                  {{ record.video_name }}
                </template>
                <div class="ellipsis-text">
                  {{ record.video_name }}
                </div>
              </a-tooltip>
              <span v-else>-</span>
            </template>
            <template v-if="column.key === 'video_popularity'">
              {{ formatNumber(+record.video_popularity) }}
            </template>
            <template v-if="column.key === 'video_price_type'">
              <a-tooltip placement="top" color="#fff">
                <template #title>
                  {{ getPriceType(record) }}
                </template>
                <div class="ellipsis-text">
                  {{ getPriceType(record) }}
                </div>
              </a-tooltip>
            </template>
          </template>
        </a-table>
      </div>
    </div>
    <template slot="footer">
      <a-button @click="addCancel">关闭</a-button>
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
import type { FilmListData, IVideoAlbum } from '@/types/site/filmList'
import { formatNumber } from '@/utils/format'
import { leftColumn, rightColumn, PRICE_TYPE, leftState } from './state'
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import Sortable from 'sortablejs'
import { storage } from '@/utils/storage'
import { message } from 'ant-design-vue'
import api from '@/apis'
const {
  site: { video_order }
} = api
type Key = string
const siteId = storage.get('siteId')
interface IProps {
  title?: string
  width?: number
  albumId: string
  visible: boolean
  type: string
  leftApiPath: (params: any) => any //左侧列表接口
  rightApiPath: (params: any) => any //已收录接口
  classApiPath: (params: any) => any //分类接口
  addApiPath: (params: any) => any //添加已收录接口
  delApiPath: (params: any) => any //删除已收录接口
}
const emit = defineEmits(['confirm', 'cancel', 'refresh-list'])
const props = withDefaults(defineProps<IProps>(), {
  visible: false,
  title: '',
  width: 1296,
  albumId: '',
  type: '影片'
})
interface IIncludesItem {
  video_id: string
  video_name: string
  video_order: string
  video_popularity: string
  video_price: string
  video_price_type: number
}
interface IState {
  filmList: FilmListData[]
  includesList: IIncludesItem[]
  rightSelectedRowKeys: Key[]
  leftSelectedRowKeys: Key[]
  classList: any
  leftLoading: boolean
  rightLoading: boolean
}
const state = reactive<IState>({
  filmList: [],
  includesList: [],
  leftSelectedRowKeys: [],
  rightSelectedRowKeys: [],
  classList: [],
  leftLoading: false,
  rightLoading: false
})
const rightKeys: any = ref([])
const queryState = reactive({
  offset: 0, // 默认当前页数
  limit: 10, // 默认当前页显示数据的大小
  total: 0 // 总数，必须先有
})
const tableRef = ref()
/**
  新建/编辑分类对话框事件
 */
const onSelectChange = (rowKeys: Key[]) => {
  console.log('leftSelectedRowKeys changed: ', rowKeys)
  state.leftSelectedRowKeys = rowKeys
}
const onSelectChange2 = (rowKeys: Key[]) => {
  console.log('rightSelectedRowKeys changed: ', rowKeys)
  state.rightSelectedRowKeys = rowKeys
}
const leftSearch = () => {
  console.log(leftState, 'leftState')
  getList()
}
/**
 * 分页改变事件
 */
const handlePaginationChange = (size: number, limit: number) => {
  queryState.limit = limit
  queryState.offset = (size - 1) * limit
  getList()
}
const toRight = () => {
  if (state.leftSelectedRowKeys.length <= 0) return message.warning('请至少选择一条数据')
  videoAddAlbum(state.leftSelectedRowKeys)
}
const toLeft = () => {
  if (state.rightSelectedRowKeys.length <= 0) return message.warning('请至少选择一条数据')
  videoDelAlbum(state.rightSelectedRowKeys)
}
//弹窗关闭事件
const handleClose = () => {
  state.leftSelectedRowKeys = []
  state.rightSelectedRowKeys = []
  emit('refresh-list')
}
const initFunc = () => {
  getList()
  getIncludesList()
  state.leftSelectedRowKeys = []
  state.rightSelectedRowKeys = []
}
//影片专辑添加影片
const videoAddAlbum = (keys: string[]) => {
  props.addApiPath({ album_id: props.albumId, video_id: keys }).then(() => {
    message.success(`添加${props.type}专辑成功`)
    // emit('confirm', false)
    initFunc()
  })
}
//影片专辑删除影片
const videoDelAlbum = (keys: string[]) => {
  props.delApiPath({ album_id: props.albumId, video_id: keys }).then(() => {
    message.success(`移除${props.type}专辑成功`)
    // emit('confirm', false)
    initFunc()
  })
}
const addCancel = () => {
  emit('cancel', false)
}
//获取影片列表
const getList = () => {
  state.leftLoading = true
  // 更新列表接口
  const params: any = {
    ...leftState,
    ...queryState
  }
  if (!params.video_id) params.video_id = undefined
  params.site_id = siteId
  params.status = 1
  props
    .leftApiPath(params)
    .then((res: any) => {
      state.filmList = res?.videos ?? []
      queryState.total = +res?.total ?? 0
      state.leftLoading = false
      //处理下一页，第一条删除问题
      if (queryState.offset >= (res?.videos ?? 0) && queryState.total != 0) {
        queryState.offset -= queryState.limit
        getList()
      }
    })
    .catch(() => {
      state.leftLoading = false
    })
}
//获取下拉分类接口
const getClassList = () => {
  props.classApiPath({ site_id: siteId, keyword: undefined, categ_status: 1 }).then((res: any) => {
    res?.categ.unshift({ id: undefined, name: '全部分类' })
    state.classList = res?.categ.map((item: any) => {
      for (var key in item) {
        if (Array.isArray(item[key]) && item[key].length === 0) {
          delete item[key]
        }
      }
      return item
    })
  })
}
//图集分类change事件
const handleSelectChange = (value: any, selectedOptions: any) => {
  console.log('value: ', value, selectedOptions)
  leftState.categ_id = value.length > 0 && value[0] ? value[0] : undefined
  leftState.subcateg_id = value.length > 0 && value[1] ? value[1] : undefined
  console.log(leftState)
}
//获取已收录影片
const getIncludesList = () => {
  state.rightLoading = true
  props
    .rightApiPath({
      album_id: props.albumId
    })
    .then((res: any) => {
      console.log(res, 'res')
      state.rightLoading = false
      state.includesList = res.videos
      rightKeys.value = res.videos.map((item: any) => item.video_id)
      // initSortable()
      // console.log('targetKeys.value: ', targetKeys.value)
    })
    .catch(() => {
      state.rightLoading = false
    })
}
const rightSelectKeys = computed(() => state.rightSelectedRowKeys.length <= 0)
const leftSelectKeys = computed(() => state.leftSelectedRowKeys.length <= 0)
//获取收费状态
const getPriceType = computed(() => (item: any) => {
  if (item.video_price_type === 1) {
    return '免费'
  } else {
    return PRICE_TYPE[item.video_price_type] + '-' + item.video_price + '金币'
  }
})
//调用排序接口
const sortFunc = (item: any) => {
  video_order({
    ...item
  }).then(() => {
    message.success('排序成功')
    getIncludesList()
  })
}
// //初始化表格拖动
// const initSortable = () => {
//   console.log('tableRef.value: ', tableRef.value)
//   const el = tableRef.value.table.$el.querySelector('#filmTable tbody') as HTMLElement
//   // const el = document.querySelector('#tableRef tbody') as HTMLElement
//   if (!el) return false
//   console.log(el, 'el')
//   new Sortable(el, {
//     handle: '.ant-table-row',
//     animation: 150,
//     ghostClass: 'blue-background-class',
//     // forceFallback: true,
//     sort: true,
//     // async
//     onEnd(item) {
//       if (item.newIndex === item.oldIndex) return
//       const startIndex = (item.oldIndex as number) - 1
//       console.log('startIndex: ', startIndex)
//       const endIndex = (item.newIndex as number) - 1
//       console.log('endIndex: ', endIndex)
//       const album_id = props.albumId
//       const { video_id } = state.includesList[startIndex]
//       const { video_order } = state.includesList[endIndex]
//       sortFunc({ album_id, video_order, video_id })
//     }
//   })
// }
// nextTick(() => {
//   initSortable()
// })
const includesLength = computed(() => state.includesList?.length ?? 0)
watch(
  () => props.visible,
  () => {
    if (!props.visible) return false
    initFunc()
    getClassList()
  },
  {
    deep: true,
    immediate: true
  }
)
//防抖
const antiShake = (time: number) => {
  return setTimeout(() => {
    console.log('防抖')
    getList()
  }, time)
}
let timer: any = null
watch(
  [() => leftState.categ_id, () => leftState.subcateg_id, () => leftState.video_id, () => leftState.video_keyword],
  (value) => {
    if (value) {
      clearTimeout(timer)
      timer = antiShake(500)
    }
  }
)
const handleOk = () => {
  emit('confirm', false)
}
const handleCancel = () => {
  emit('cancel')
}
onMounted(() => {
  // nextTick(() => {
  //   initSortable()
  // })
})
</script>

<style lang="less" scoped>
:deep(.childBg) {
  background-color: #f5f5f5;
}
.leftTable {
  border: 1px solid rgba(217, 217, 217, 1);
  border-radius: 2px;
  &-title {
    height: 39px;
    border-bottom: 1px solid rgba(217, 217, 217, 1);
    padding: 9px 16px;
    box-sizing: border-box;
  }
}
.rightTable {
  border: 1px solid rgba(217, 217, 217, 1);
  border-radius: 2px;
  &-title {
    height: 39px;
    border-bottom: 1px solid rgba(217, 217, 217, 1);
    padding: 9px 16px;
    box-sizing: border-box;
  }
}
:deep(.ant-modal-footer .ant-btn) {
  display: none !important;
}
.ellipsis-text {
  max-width: 100px !important;
  white-space: nowrap;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: pointer;
}
</style>
